import os.path,sys
#TODO:implement id3 copying using import mutagen
#



is_mp3=lambda s: (len(s)-4)==s.find('.mp3')

def mk_intro_mp3(mp3file,start='0.0.0',end='0.59.0',folder='c:\intros'):
    (storage,filename)=os.path.split(os.path.abspath(mp3file))
#    folder=os.path.abspath(folder)

#let's create directory
    newstorage=folder+storage
    if sys.platform =='win32':
        
        newstorage=folder+os.path.splitdrive(os.path.abspath(storage))[1]
    
    newstorage=os.path.abspath(newstorage)    
    
    if not os.path.exists(newstorage) :
        os.makedirs(newstorage)    

#we shall implement the following:
#mp3splt -d c:\tmp\directory C:\sourcedir\albumz\songname.mp3 0.0.0 2.0.0 -o songname.mp3

    mp3cmd ='mp3splt -f -d "%s" "%s" %s %s -o "%s" ' % \
     ( newstorage, mp3file, start, end, filename)

    print mp3cmd    
    os.system(mp3cmd) 
    
    #fixing plussed filenames :( by renaming  '+'  to ' '
    if mp3file.find('+')>-1:
        deplussed=filename.replace('+',' ')
        
        deplussed=os.path.abspath(newstorage+os.sep+deplussed)
        plused=  os.path.abspath(newstorage+os.sep+filename)
        
        print '\ndeplusssing:', deplussed, plused
        os.rename(deplussed, plused)
 

 
 
def mk_intros(filelist,start='0.0.0',end='0.5.0',folder='.\intros'):        
    for f in filter(is_mp3,filelist):
        mk_intro_mp3(f,start,end,folder)

import unittest    

class dotests(unittest.TestCase):
    def setUp(self):
        print 'seting Up tests %s ' % self.id()
    def test_mk_intro_mp3(self):
        drive=os.path.splitdrive(os.path.abspath('.'))[0]
        mk_intro_mp3(mp3file='../data/test.mp3', \
                          start='0.0.0', end='0.5.0', 
                          folder=drive+'/tmp/test_mk_intro_mp3')

        
            
    def test_clone_intros(self):
        filelist=open('../data/authors.lst').read().split('\n')
        
        mk_intros(filelist,start='0.0.0',end='0.15.0',folder='/tmp/intros')
        

        filelist1=[]
        filelist2=[]
        for f in filelist: filelist1.append(os.path.split(f)[1])                        
        for f in os.walk('/tmp/intros'): filelist2=filelist2+f[2]
        
        print self.assertEqual(filelist1.sort(),filelist2.sort())
#        print self.assertEqual(2,1)
        
        
    def tearDown(self):
        print '%s tests completed' % self.id()
        

if __name__=='__main__':
    unittest.main()             